{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Tce3stUlHN0L"
      },
      "source": [
        "##### Copyright 2025 Google LLC."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "tuOe1ymfHZPu"
      },
      "outputs": [],
      "source": [
        "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "b9nJzRUxezMZ"
      },
      "source": [
        "# Gemini API: Streaming Quickstart with REST"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "c86847414779"
      },
      "source": [
        "<a target=\"_blank\" href=\"https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/rest/Streaming_REST.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" height=30/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "651ff3039fc8"
      },
      "source": [
        "If you want to quickly try out the Gemini API, you can use `curl` commands to call the methods in the REST API.\n",
        "\n",
        "This notebook contains `curl` commands you can run in Google Colab, or copy to your terminal.\n",
        "\n",
        "To run this notebook, your API key must be stored it in a Colab Secret named GOOGLE_API_KEY. If you are running in a different environment, you can store your key in an environment variable. See [Authentication](https://github.com/google-gemini/cookbook/blob/main/quickstarts/Authentication.ipynb) to learn more."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "kdNfwWxaewah"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "from google.colab import userdata"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "8zRWJLPEe6MD"
      },
      "outputs": [],
      "source": [
        "os.environ['GOOGLE_API_KEY'] = userdata.get('GOOGLE_API_KEY')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "InqXD9BZe_-I"
      },
      "source": [
        "### Stream Generate Content\n",
        "\n",
        "By default, the model returns a response after completing the entire generation process. You can achieve faster interactions by not waiting for the entire result, and instead use streaming to handle partial results.\n",
        "\n",
        "**Important**: Set `alt=sse` in your URL parameters when running the cURL command (<code>streamGenerateContent?<strong>alt=sse</string></code> below). With `sse` each stream chunk is a [GenerateContentResponse](https://ai.google.dev/api/rest/v1beta/GenerateContentResponse) object with a portion of the output text in `candidates[0].content.parts[0].text`. Without `sse` it str\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "81058752991d"
      },
      "outputs": [],
      "source": [
        "MODEL_ID = \"gemini-2.5-flash\" # @param [\"gemini-2.5-flash-lite\", \"gemini-2.5-flash\", \"gemini-2.5-pro\",\"gemini-3-pro-preview\"] {\"allow-input\":true, isTemplate: true}"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "FN99wX6ye_dt"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "data: {\"candidates\": [{\"content\": {\"parts\": [{\"text\": \"In the quaint, sunlit cottage nestled amidst a lush meadow, resided two feline\"}],\"role\": \"model\"},\"finishReason\": \"STOP\",\"index\": 0,\"safetyRatings\": [{\"category\": \"HARM_CATEGORY_SEXUALLY_EXPLICIT\",\"probability\": \"NEGLIGIBLE\"},{\"category\": \"HARM_CATEGORY_HATE_SPEECH\",\"probability\": \"NEGLIGIBLE\"},{\"category\": \"HARM_CATEGORY_HARASSMENT\",\"probability\": \"NEGLIGIBLE\"},{\"category\": \"HARM_CATEGORY_DANGEROUS_CONTENT\",\"probability\": \"NEGLIGIBLE\"}]}],\"promptFeedback\": {\"safetyRatings\": [{\"category\": \"HARM_CATEGORY_SEXUALLY_EXPLICIT\",\"probability\": \"NEGLIGIBLE\"},{\"category\": \"HARM_CATEGORY_HATE_SPEECH\",\"probability\": \"NEGLIGIBLE\"},{\"category\": \"HARM_CATEGORY_HARASSMENT\",\"probability\": \"NEGLIGIBLE\"},{\"category\": \"HARM_CATEGORY_DANGEROUS_CONTENT\",\"probability\": \"NEGLIGIBLE\"}]}}\r\n",
            "\n",
            "data: {\"candidates\": [{\"content\": {\"parts\": [{\"text\": \" companions named Mittens and Whiskers. Mittens, with her silky black fur and piercing green eyes, possessed an air of elegance and mystery. Whiskers,\"}],\"role\": \"model\"},\"finishReason\": \"STOP\",\"index\": 0,\"safetyRatings\": [{\"category\": \"HARM_CATEGORY_SEXUALLY_EXPLICIT\",\"probability\": \"NEGLIGIBLE\"},{\"category\": \"HARM_CATEGORY_HATE_SPEECH\",\"probability\": \"NEGLIGIBLE\"},{\"category\": \"HARM_CATEGORY_HARASSMENT\",\"probability\": \"NEGLIGIBLE\"},{\"category\": \"HARM_CATEGORY_DANGEROUS_CONTENT\",\"probability\": \"NEGLIGIBLE\"}]}]}\n",
            "\n",
            "data: {\"candidates\": [{\"content\": {\"parts\": [{\"text\": \" on the other hand, was a playful and mischievous white tomcat with a penchant for chasing his tail.\\n\\nOne lazy afternoon, as the sun cast long shadows across the meadow, Mittens and Whiskers found themselves lounging comfortably in the windowsill. The warm breeze carried the scent of blooming wildflowers, filling the room with\"}],\"role\": \"model\"},\"finishReason\": \"STOP\",\"index\": 0,\"safetyRatings\": [{\"category\": \"HARM_CATEGORY_SEXUALLY_EXPLICIT\",\"probability\": \"NEGLIGIBLE\"},{\"category\": \"HARM_CATEGORY_HATE_SPEECH\",\"probability\": \"NEGLIGIBLE\"},{\"category\": \"HARM_CATEGORY_HARASSMENT\",\"probability\": \"NEGLIGIBLE\"},{\"category\": \"HARM_CATEGORY_DANGEROUS_CONTENT\",\"probability\": \"NEGLIGIBLE\"}]}]}\n",
            "\n",
            "data: {\"candidates\": [{\"content\": {\"parts\": [{\"text\": \" a sweet fragrance.\\n\\n\\\"My, what a lovely day it is,\\\" Mittens purred contently. \\\"I could stay here forever, basking in the sunshine.\\\"\\n\\n\\\"Oh, come on, Mittens!\\\" Whiskers exclaimed, his tail twitching with excitement. \\\"Let's go on an adventure!\\\"\\n\\nWith a reluctant sigh, Mittens agreed. Together, they leaped from the windowsill and landed gracefully in the long grass.\\n\\nAs they explored the meadow, they encountered a family of fluffy bunnies hopping merrily through the daisies. Whiskers couldn't resist chasing after them, his whiskers twitching with glee.\"}],\"role\": \"model\"},\"finishReason\": \"STOP\",\"index\": 0,\"safetyRatings\": [{\"category\": \"HARM_CATEGORY_SEXUALLY_EXPLICIT\",\"probability\": \"NEGLIGIBLE\"},{\"category\": \"HARM_CATEGORY_HATE_SPEECH\",\"probability\": \"NEGLIGIBLE\"},{\"category\": \"HARM_CATEGORY_HARASSMENT\",\"probability\": \"NEGLIGIBLE\"},{\"category\": \"HARM_CATEGORY_DANGEROUS_CONTENT\",\"probability\": \"NEGLIGIBLE\"}]}]}\n",
            "\n",
            "data: {\"candidates\": [{\"content\": {\"parts\": [{\"text\": \" Mittens, however, took a more leisurely approach, stopping to admire the vibrant wildflowers.\\n\\nSuddenly, their peaceful adventure was interrupted by the sound of a loud crash. They turned in alarm and saw that a large branch had fallen from a nearby tree, blocking the path.\\n\\n\\\"Oh no!\\\" Mittens cried in dismay. \\\"We're trapped!\\\"\\n\\nWhiskers, with his usual optimism, said, \\\"Don't worry, Mittens. I have a plan.\\\"\\n\\nSwiftly, he scurried up the trunk of the tree and used his sharp claws to dislodge the branch. With a mighty shove, he sent it crashing to the ground, clearing the way.\\n\\nMittens was overjoyed. \\\"Thank you, Whiskers!\\\" she said, purring. \\\"You saved the day.\\\"\\n\\nTogether, they continued their adventure, their bond strengthened by their shared experience. As the sun began to set, they made their way back to the cottage, tired but content.\\n\\nFrom that day forward, Mittens and Whiskers became known as the \\\"冒险伙伴\\\" (Adventure Buddies) of the meadow, their legend passed down through generations of kittens. And so, in that quaint little cottage, they lived happily ever after, their love for each\"}],\"role\": \"model\"},\"finishReason\": \"STOP\",\"index\": 0,\"safetyRatings\": [{\"category\": \"HARM_CATEGORY_SEXUALLY_EXPLICIT\",\"probability\": \"NEGLIGIBLE\"},{\"category\": \"HARM_CATEGORY_HATE_SPEECH\",\"probability\": \"NEGLIGIBLE\"},{\"category\": \"HARM_CATEGORY_HARASSMENT\",\"probability\": \"NEGLIGIBLE\"},{\"category\": \"HARM_CATEGORY_DANGEROUS_CONTENT\",\"probability\": \"NEGLIGIBLE\"}]}]}\n",
            "\n",
            "data: {\"candidates\": [{\"content\": {\"parts\": [{\"text\": \" other and for adventure stronger than ever.\"}],\"role\": \"model\"},\"finishReason\": \"STOP\",\"index\": 0,\"safetyRatings\": [{\"category\": \"HARM_CATEGORY_SEXUALLY_EXPLICIT\",\"probability\": \"NEGLIGIBLE\"},{\"category\": \"HARM_CATEGORY_HATE_SPEECH\",\"probability\": \"NEGLIGIBLE\"},{\"category\": \"HARM_CATEGORY_HARASSMENT\",\"probability\": \"NEGLIGIBLE\"},{\"category\": \"HARM_CATEGORY_DANGEROUS_CONTENT\",\"probability\": \"NEGLIGIBLE\"}]}]}\n",
            "\n"
          ]
        }
      ],
      "source": [
        "!curl \"https://generativelanguage.googleapis.com/v1beta/models/${MODEL_ID}:streamGenerateContent?alt=sse&key=${GOOGLE_API_KEY}\" \\\n",
        "        -H 'Content-Type: application/json' \\\n",
        "        --no-buffer \\\n",
        "        -d '{ \"contents\":[{\"parts\":[{\"text\": \"Write a cute story about cats.\"}]}]}'"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "name": "Streaming_REST.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
